package controllers;

import helpers.LanguageHelper;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import search.ArticleSearchEngine;
import systems.Recently;

import entities.Article;
import entities.ArticleSearch;

import models.ArticleModel;

public class AcceptArticleServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String id = (String) request.getParameter("id");
		String key = (String) request.getParameter("key");
		String action = (String) request.getParameter("action");
		
		LanguageHelper translate = (LanguageHelper) request.getAttribute("translate");
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = articleModel.getArticle(id);
		if (action != null && article != null) {
			article.setPublished(true);
			article.setStatus(1);
			articleModel.insert(article);
			
			//Set search article
			ArticleSearch articleSearch = ArticleSearch.convert(article);
			ArticleSearchEngine.update(articleSearch);
			
			//Remove recently cache
			Recently.update(article);
			request.setAttribute("success", translate.getString("accept_success_message"));
		}
		
		if (article != null && !article.getAuthKey().equals(key)) {
			article = null;
		}
		
		request.setAttribute("article", article);
		try {
			request.getRequestDispatcher("/pages/accept_article.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
